/**
 * 百炼客户端 JavaScript 模块
 * 用于在浏览器中与百炼 API 进行通信
 */

// 创建百炼客户端对象
const BailianClient = {
  /**
   * 生成文本补全
   * @param {string} prompt - 提示文本
   * @param {number} maxTokens - 最大标记数
   * @param {number} temperature - 温度参数
   * @returns {Promise<Object>} - API 响应
   */
  async generateCompletion(prompt, maxTokens = 1024, temperature = 0.7) {
    try {
      const response = await fetch('/api/bailian/completion', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          prompt,
          maxTokens,
          temperature
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to generate completion');
      }

      return await response.json();
    } catch (error) {
      console.error('Error generating completion:', error);
      throw error;
    }
  },

  /**
   * 生成聊天回复
   * @param {Array} messages - 消息数组
   * @param {number} maxTokens - 最大标记数
   * @param {number} temperature - 温度参数
   * @returns {Promise<Object>} - API 响应
   */
  async generateChat(messages, maxTokens = 1024, temperature = 0.7) {
    try {
      const response = await fetch('/api/bailian/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          messages,
          maxTokens,
          temperature
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to generate chat');
      }

      return await response.json();
    } catch (error) {
      console.error('Error generating chat:', error);
      throw error;
    }
  },

  /**
   * 分析图片
   * @param {FormData} formData - 包含图片和参数的表单数据
   * @returns {Promise<Object>} - API 响应
   */
  async analyzeImage(formData) {
    try {
      const response = await fetch('/api/bailian/image-analysis', {
        method: 'POST',
        body: formData
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to analyze image');
      }

      return await response.json();
    } catch (error) {
      console.error('Error analyzing image:', error);
      throw error;
    }
  },

  /**
   * 检查 API 状态
   * @returns {Promise<Object>} - API 状态
   */
  async checkStatus() {
    try {
      console.log('Checking API status...');
      const response = await fetch('/api/bailian/status');

      console.log('API status response:', response);

      if (!response.ok) {
        console.error('API status check failed with status:', response.status);
        throw new Error(`API status check failed with status: ${response.status}`);
      }

      const data = await response.json();
      console.log('API status data:', data);
      return data;
    } catch (error) {
      console.error('Error checking API status:', error);
      throw error;
    }
  }
};

// 导出客户端对象
window.BailianClient = BailianClient;
